﻿using BroadGoalComponents.BGControls.Toast;
using BroadGoalComponents.Dialogs;
using Custom.Controls;
using Custom.Framework;
using Custom.Infrastructure.EventBus;
using Custom.Model.Entity;
using Custom.Service.Repository;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Custom.Business.Sale
{
    public partial class frmSaleAdd : PopupForm, IEventHandler<TEventEntity>
    {
        protected DataGridViewTextBoxEditingControl dgvTxt = null;
        protected frmSaleCustomSearch customFrm = null;
        // 选择的客户id
        private int selectedCusId = 0;

        /// <summary>
        /// 构造函数：初始化
        /// </summary>
        public frmSaleAdd()
        {
            InitializeComponent();

            EventBus.Instance.Subscribe(this);

            this.bgDataGridView1.TopLeftHeaderCell.Value = "序号";
            this.bgDataGridView1.RowHeadersWidth = 55;
            this.bgDataGridView1.RowHeadersVisible = true;
            this.bgDataGridView1.ShowLineNo = true;
        }

        /// <summary>
        /// 初始化初始行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmSaleAdd_Load(object sender, EventArgs e)
        {
            this.initDetail();
        }

        /// <summary>
        /// 点击会员名称：弹出会员信息选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCusname_Click(object sender, EventArgs e)
        {
            if (this.customFrm == null || this.customFrm.IsDisposed)
            {
                this.customFrm = new frmSaleCustomSearch();
                this.customFrm.StartPosition = FormStartPosition.Manual;
                customFrm.Location = this.PointToScreen(new Point(this.txtCusname.Location.X, this.txtCusname.Location.Y + this.txtCusname.Height + 2));
            }
            this.customFrm.Show(this);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            this.saveData();
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 操作列按钮功能实现
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgDataGridView1_ActionButtonClick(object sender, BroadGoalComponents.BGControls.ActionButtonEventArgs e)
        {
            int rowIndex = this.bgDataGridView1.CurrentRow.Index;

            if (rowIndex < 0) return;

            switch (e.ButtonName)
            {
                case "+":
                    this.addRow(rowIndex + 1);
                    break;
                case "-":
                    this.delRow(rowIndex);
                    break;
            }
        }

        /// <summary>
        /// 实时计算金额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgDataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            if (e.ColumnIndex != this.col_price.Index && e.ColumnIndex != this.col_quantity.Index) return;

            decimal price = decimal.Zero;
            decimal quantity = decimal.Zero;

            decimal.TryParse(this.bgDataGridView1.Rows[e.RowIndex].Cells[this.col_price.Name].Value?.ToString(), out price);
            decimal.TryParse(this.bgDataGridView1.Rows[e.RowIndex].Cells[this.col_quantity.Name].Value?.ToString(), out quantity);


            this.bgDataGridView1.Rows[e.RowIndex].Cells[this.col_price.Name].Value = price.ToString("0.00");
            this.bgDataGridView1.Rows[e.RowIndex].Cells[this.col_amount.Name].Value = (price * quantity).ToString("0.00");

            this.calculateTotalAmount();
        }

        /// <summary>
        /// 限定单价和数量列只能输入数字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgDataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            dgvTxt = (DataGridViewTextBoxEditingControl)e.Control; // 赋值  
            dgvTxt.SelectAll();
            dgvTxt.KeyPress += Cells_KeyPress;
        }

        /// <summary>
        /// 限定单价和数量列只能输入数字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cells_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this.bgDataGridView1.CurrentCell.ColumnIndex != this.col_price.Index &&
                   this.bgDataGridView1.CurrentCell.ColumnIndex != this.col_quantity.Index)
            {
                return;
            }

            if (char.IsNumber(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == (char)Keys.Back)
            {
                e.Handled = false;       //让操作生效
                int j = 0;
                int k = 0;
                bool flag = false;
                if (dgvTxt.Text.Length == 0)
                {
                    if (e.KeyChar == '.')
                    {
                        e.Handled = true;             //让操作失效
                    }
                }
                for (int i = 0; i < dgvTxt.Text.Length; i++)
                {
                    if (dgvTxt.Text[i] == '.')
                    {
                        j++;
                        flag = true;
                    }
                    if (flag)
                    {
                        if (char.IsNumber(dgvTxt.Text[i]) && e.KeyChar != (char)Keys.Back)
                        {
                            k++;
                        }
                    }
                    if (j >= 1)
                    {
                        if (e.KeyChar == '.')
                        {
                            e.Handled = true;             //让操作失效
                        }
                    }
                    if (k == 2)
                    {
                        if (char.IsNumber(dgvTxt.Text[i]) && e.KeyChar != (char)Keys.Back)
                        {
                            if (dgvTxt.Text.Length - dgvTxt.SelectionStart < 3)
                            {
                                if (dgvTxt.SelectedText != dgvTxt.Text)
                                {
                                    e.Handled = true;             ////让操作失效
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                e.Handled = true;
            }
        }

        /// <summary>
        /// 窗体激活时关闭客户查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmSaleAdd_Activated(object sender, EventArgs e)
        {
            if (this.customFrm != null && !this.customFrm.IsDisposed)
            {
                this.customFrm.Close();
            }
        }

        /// <summary>
        /// 取消注册事件总线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmSaleAdd_FormClosed(object sender, FormClosedEventArgs e)
        {
            EventBus.Instance.UnSubscribe(this);
        }

        /// <summary>
        /// 事件总线处理方法
        /// </summary>
        /// <param name="evt"></param>
        public void HandleEvent(TEventEntity evt)
        {
            switch (evt.ActionName)
            {
                case "selectcustom":
                    this.onSelectCustom(int.Parse(evt.Data.ToString()));
                    break;
            }
        }

        /// <summary>
        /// 设置选择的客户信息
        /// </summary>
        /// <param name="id"></param>
        private void onSelectCustom(int id)
        {
            CustomInfo custom = new CustomInfoRepository().Get(id);
            if (custom == null) return;

            this.txtCardNo.Enabled = true;
            this.txtIdentityNo.Enabled = true;
            this.txtMobile.Enabled = true;
            this.selectedCusId = custom.id;
            this.txtCusname.Text = custom.cusname;
            this.txtCardNo.Text = custom.cardno;
            this.txtIdentityNo.Text = custom.identityno;
            this.txtMobile.Text = custom.mobile;
            this.txtCardNo.Enabled = false;
            this.txtIdentityNo.Enabled = false;
            this.txtMobile.Enabled = false;
            this.btnSave.Focus();
            this.btnSave.Select();
        }

        /// <summary>
        /// 初始化数据行
        /// </summary>
        private void initDetail()
        {
            this.addRow(0);
        }

        /// <summary>
        /// 新增1行
        /// </summary>
        /// <param name="rowIndex"></param>
        private void addRow(int rowIndex)
        {
            this.bgDataGridView1.Rows.Insert(rowIndex);
            this.bgDataGridView1.Rows[rowIndex].Cells[this.col_quantity.Name].Value = 1;
        }

        /// <summary>
        /// 删除指定行
        /// </summary>
        /// <param name="rowIndex"></param>
        private void delRow(int rowIndex)
        {
            this.bgDataGridView1.Rows.RemoveAt(rowIndex);

            this.calculateTotalAmount();
        }

        private void saveData()
        {
            if (!this.checkData()) return;

            long id = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmssfff"));

            try
            {
                SaleInfo sale = new SaleInfo()
                {
                    id = id,
                    cusid = this.selectedCusId,
                    cusname = this.txtCusname.Text.Trim(),
                    cardno = this.txtCardNo.Text.Trim(),
                    identityno = this.txtIdentityNo.Text.Trim(),
                    mobile = this.txtMobile.Text.Trim(),
                    totalamount = decimal.Parse(this.lbTotalAmount.Text.Replace("合计金额：", "").Replace("元", "")),
                    createtime = DateTime.Now
                };

                List<SaleDetail> details = new List<SaleDetail>();
                for (int i = 0; i < this.bgDataGridView1.RowCount; i++)
                {
                    string spmc = this.bgDataGridView1.Rows[i].Cells[this.col_name.Name].Value?.ToString();
                    decimal price = decimal.Zero;
                    decimal quantity = decimal.Zero;
                    decimal amount = decimal.Zero;
                    decimal.TryParse(this.bgDataGridView1.Rows[i].Cells[this.col_price.Name].Value?.ToString(), out price);
                    decimal.TryParse(this.bgDataGridView1.Rows[i].Cells[this.col_quantity.Name].Value?.ToString(), out quantity);
                    decimal.TryParse(this.bgDataGridView1.Rows[i].Cells[this.col_amount.Name].Value?.ToString(), out amount);

                    SaleDetail d = new SaleDetail()
                    {
                        saleid = id,
                        name = spmc,
                        price = price,
                        quantity = quantity,
                        amount = amount
                    };
                    details.Add(d);
                }

                new SaleInfoRepository().Insert(sale, details);

                BGToast.Show("保存成功");

                this.Close();
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                WarningDialog.Show("保存出错啦");
            }
        }

        /// <summary>
        /// 检查数据
        /// </summary>
        /// <returns></returns>
        private bool checkData()
        {
            if (string.IsNullOrEmpty(this.txtCusname.Text.Trim()))
            {
                WarningDialog.Show("请选择会员");
                return false;
            }

            for (int i = 0; i < this.bgDataGridView1.RowCount; i++)
            {
                string spmc = this.bgDataGridView1.Rows[i].Cells[this.col_name.Name].Value?.ToString();
                decimal price = decimal.Zero;
                decimal quantity = decimal.Zero;
                decimal.TryParse(this.bgDataGridView1.Rows[i].Cells[this.col_price.Name].Value?.ToString(), out price);
                decimal.TryParse(this.bgDataGridView1.Rows[i].Cells[this.col_quantity.Name].Value?.ToString(), out quantity);
                if (string.IsNullOrEmpty(spmc))
                {
                    WarningDialog.Show($"第{i+ 1}行：商品名称不能为空");
                    return false;
                }
                if (price == decimal.Zero)
                {
                    WarningDialog.Show($"第{i + 1}行：单价必须大于0");
                    return false;
                }
                if (quantity == decimal.Zero)
                {
                    WarningDialog.Show($"第{i + 1}行：数量必须大于0");
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 计算总金额
        /// </summary>
        private void calculateTotalAmount()
        {
            // 计算合计金额
            decimal total_amount = decimal.Zero;
            for (int i = 0; i < this.bgDataGridView1.RowCount; i++)
            {
                decimal amount = decimal.Zero;
                decimal.TryParse(this.bgDataGridView1.Rows[i].Cells[this.col_amount.Name].Value?.ToString(), out amount);
                total_amount += amount;
            }
            this.lbTotalAmount.Text = "合计金额：" + total_amount.ToString("0.00") + " 元";
        }

    }
}
